package com.cencat.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cencat.order.entity.Order;
import com.cencat.order.mapper.OrderMapper;
import com.cencat.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 订单服务实现类
 * 
 * @author cencat
 * @version 1.0
 * @since 2024-12-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public IPage<Order> getOrderPage(Page<Order> page, Integer orderStatus, Integer orderType, 
                                    LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.selectOrderPage(page, orderStatus, orderType, startTime, endTime);
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("is_deleted", 0);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    public IPage<Order> getOrdersByUserId(Long userId, Integer orderStatus, Page<Order> page) {
        return orderMapper.selectOrdersByUserId(page, userId, orderStatus);
    }

    @Override
    public IPage<Order> getOrdersByDriverId(Long driverId, Integer orderStatus, Page<Order> page) {
        return orderMapper.selectOrdersByDriverId(page, driverId, orderStatus);
    }

    @Override
    public boolean createOrder(Order order) {
        // 设置订单创建时间
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setIsDeleted(0);
        
        // 生成订单号
        if (order.getOrderNo() == null || order.getOrderNo().isEmpty()) {
            order.setOrderNo(generateOrderNo());
        }
        
        return orderMapper.insert(order) > 0;
    }

    @Override
    public boolean updateOrderStatus(Long orderId, Integer orderStatus, LocalDateTime updateTime) {
        return orderMapper.updateOrderStatus(orderId, orderStatus, updateTime) > 0;
    }

    @Override
    public boolean assignDriver(Long orderId, Long driverId, LocalDateTime updateTime) {
        return orderMapper.assignDriver(orderId, driverId, updateTime) > 0;
    }

    @Override
    public boolean updateOrderAmount(Long orderId, java.math.BigDecimal totalAmount, LocalDateTime updateTime) {
        return orderMapper.updateOrderAmount(orderId, totalAmount, updateTime) > 0;
    }

    @Override
    public boolean cancelOrder(Long orderId, String cancelReason, LocalDateTime updateTime) {
        return orderMapper.cancelOrder(orderId, cancelReason, updateTime) > 0;
    }

    @Override
    public boolean completeOrder(Long orderId, java.math.BigDecimal actualAmount, LocalDateTime completedTime) {
        return orderMapper.completeOrder(orderId, actualAmount, completedTime) > 0;
    }

    @Override
    public Long countOrders(Integer orderStatus, Integer orderType, LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.countOrders(orderStatus, orderType, startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getOrderStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.getOrderStatistics(startTime, endTime);
    }

    @Override
    public Map<String, Object> getUserOrderStats(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.getUserOrderStats(userId, startTime, endTime);
    }

    @Override
    public Map<String, Object> getDriverOrderStats(Long driverId, LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.getDriverOrderStats(driverId, startTime, endTime);
    }

    @Override
    public Map<String, Object> getOrderIncomeStats(LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.getOrderIncomeStats(startTime, endTime);
    }

    @Override
    public List<Map<String, Object>> getPopularRouteStats(LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
        return orderMapper.getPopularRouteStats(startTime, endTime, limit);
    }

    @Override
    public Map<String, Object> getOrderRatingStats(LocalDateTime startTime, LocalDateTime endTime) {
        return orderMapper.getOrderRatingStats(startTime, endTime);
    }

    @Override
    public boolean batchUpdateOrderStatus(List<Long> orderIds, Integer orderStatus, LocalDateTime updateTime) {
        return orderMapper.batchUpdateOrderStatus(orderIds, orderStatus, updateTime) > 0;
    }

    @Override
    public List<Order> getTimeoutOrders(Integer timeoutMinutes) {
        return orderMapper.getTimeoutOrders(timeoutMinutes);
    }

    @Override
    public List<Order> getPendingAssignOrders(Integer limit) {
        return orderMapper.getPendingAssignOrders(limit);
    }

    @Override
    public List<Order> getActiveOrders(Long driverId) {
        return orderMapper.getActiveOrders(driverId);
    }

    @Override
    public List<Map<String, Object>> getSmartOrderRecommendation(Long driverId, java.math.BigDecimal latitude, 
                                                                java.math.BigDecimal longitude, Integer limit) {
        return orderMapper.getSmartOrderRecommendation(driverId, latitude, longitude, limit);
    }

    @Override
    public List<Map<String, Object>> getOrderTrajectory(Long orderId) {
        return orderMapper.getOrderTrajectory(orderId);
    }

    @Override
    public boolean updateOrderLocation(Long orderId, java.math.BigDecimal currentLatitude, 
                                      java.math.BigDecimal currentLongitude, LocalDateTime updateTime) {
        return orderMapper.updateOrderLocation(orderId, currentLatitude, currentLongitude, updateTime) > 0;
    }

    /**
     * 生成订单号
     * 格式：ORD + 年月日 + 6位随机数
     * 
     * @return 订单号
     */
    private String generateOrderNo() {
        String dateStr = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomStr = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        return "ORD" + dateStr + randomStr;
    }

}